package com.af;

import android.content.Context;
import android.opengl.GLSurfaceView;
import android.util.AttributeSet;
import android.util.Log;

import javax.microedition.khronos.egl.EGL10;
import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.egl.EGLContext;
import javax.microedition.khronos.egl.EGLDisplay;
import javax.microedition.khronos.opengles.GL10;

class AFView extends GLSurfaceView
{
    static {
        System.loadLibrary("af_view");
    }
    public static native void nativeSurfaceChanged(int width, int height);
    public static native void nativeDrawFrame();
    public static native void nativeDestroyContext();
    
    private static String TAG = "Asteroids";
    
    public AFView(Context context)
    {
    	super(context);
    	init();
    }

    public AFView(Context context, AttributeSet attrs)
    {
        super(context, attrs);
        init();
    }
    
    private void init()
    {
        setEGLContextFactory(new ContextFactory());
        setRenderer(new Renderer());
    }

    private static class ContextFactory implements GLSurfaceView.EGLContextFactory
    {
        private static int EGL_CONTEXT_CLIENT_VERSION = 0x3098;
        
        public EGLContext createContext(EGL10 egl, EGLDisplay display, EGLConfig eglConfig)
        {
            Log.i(TAG, "Create OpenGL ES 2.0 context");
            
            int[] attrib_list = {
            		EGL_CONTEXT_CLIENT_VERSION, 2,
            		EGL10.EGL_NONE
            };
            
            EGLContext context = egl.eglCreateContext(display, eglConfig, EGL10.EGL_NO_CONTEXT, attrib_list);
            return context;
        }

        public void destroyContext(EGL10 egl, EGLDisplay display, EGLContext context)
        {
            Log.i(TAG, "Destroy OpenGL ES 2.0 context");
            egl.eglDestroyContext(display, context);
            nativeDestroyContext();
        }
    }

    private static class Renderer implements GLSurfaceView.Renderer
    {
        public void onDrawFrame(GL10 gl)
        {
            nativeDrawFrame();
        }

        public void onSurfaceChanged(GL10 gl, int width, int height)
        {
            nativeSurfaceChanged(width, height);
        }

        public void onSurfaceCreated(GL10 gl, EGLConfig config)
        {
            Log.i(TAG, "Surface created");
        }
    }
}
